// 创建场景、相机和渲染器
function initModelViewer(containerId = 'model-container') {
    // 变量声明 - 用于头部跟踪
    let robotHeads = []; // 存储所有模型的头部
    let mouseX = 0;
    let mouseY = 0;
    let windowHalfX = window.innerWidth / 2;
    let windowHalfY = window.innerHeight / 2;
    let headRotationLimitX = Math.PI / 4; // 水平旋转限制 (45度)
    let headRotationLimitY = Math.PI / 6; // 垂直旋转限制 (30度)
    
    // 创建容器（如果不存在）
    let container = document.getElementById(containerId);
    if (!container) {
        container = document.createElement('div');
        container.id = containerId;
        container.style.width = '100%';
        container.style.height = '500px';
        document.body.appendChild(container);
    }

    // 创建场景
    const scene = new THREE.Scene();
    // 设置图片背景
    setBackgroundImage(scene, '../img/bk.png');

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
        75,                                     // 视野角度
        container.clientWidth / container.clientHeight, // 宽高比
        0.1,                                    // 近裁剪面
        1000                                    // 远裁剪面
    );
    camera.position.set(0, 1, 5);

    // 创建渲染器
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);

    // 添加环境光和平行光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(5, 10, 7.5);
    directionalLight.castShadow = true;
    scene.add(directionalLight);
    
    // 添加环境贴图（提高材质的真实感）
    const envMapLoader = new THREE.CubeTextureLoader();
    const envMap = envMapLoader.load([
        './textures/cube/Park2/posx.jpg',
        './textures/cube/Park2/negx.jpg',
        './textures/cube/Park2/posy.jpg',
        './textures/cube/Park2/negy.jpg',
        './textures/cube/Park2/posz.jpg',
        './textures/cube/Park2/negz.jpg'
    ]);
    scene.environment = envMap;

    // 添加网格地面
    const gridHelper = new THREE.GridHelper(20, 20);
    gridHelper.position.y = 0;
    scene.add(gridHelper);

    // 创建轨道控制器
    let controls;
    if (THREE.OrbitControls) {
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true;
        controls.dampingFactor = 0.05;
    }

    // 存储所有加载的模型
    const loadedModels = [];

    // 处理窗口大小变化
    window.addEventListener('resize', onWindowResize);
    
    // 添加鼠标移动监听器
    document.addEventListener('mousemove', onDocumentMouseMove);
    
    function onDocumentMouseMove(event) {
        // 计算鼠标位置（相对于窗口中心的归一化坐标）
        mouseX = (event.clientX - windowHalfX) / windowHalfX;
        mouseY = (event.clientY - windowHalfY) / windowHalfY;
    }
    
    function onWindowResize() {
        windowHalfX = window.innerWidth / 2;
        windowHalfY = window.innerHeight / 2;
        camera.aspect = container.clientWidth / container.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(container.clientWidth, container.clientHeight);
    }

    // 动画循环
    function animate() {
        requestAnimationFrame(animate);
        
        // 更新所有头部旋转
        updateHeadRotations();
        
        if (controls) {
            controls.update();
        }
        
        renderer.render(scene, camera);
    }
    
    // 更新所有头部旋转的函数
    function updateHeadRotations() {
        robotHeads.forEach(headInfo => {
            const robotHead = headInfo.head;
            const initial = headInfo.initialRotation;
            
            // 根据鼠标位置计算目标旋转
            const targetRotationY = initial.y + (mouseX * headRotationLimitX);
            const targetRotationX = initial.x + (mouseY * headRotationLimitY);
            
            // 使用线性插值实现平滑过渡
            robotHead.rotation.y += (targetRotationY - robotHead.rotation.y) * 0.05;
            robotHead.rotation.x += (targetRotationX - robotHead.rotation.x) * 0.05;
        });
    }
    
    // 启动动画循环
    animate();
    
    // 提供一个公共方法来加载模型
    return {
        loadModel: function(modelUrl, position = { x: 0, y: 0, z: 0 }, scale = 1.0) {
            // 检测文件类型 (.gltf 或 .glb)
            const isGLB = modelUrl.toLowerCase().endsWith('.glb');
            
            // 加载模型
            const loader = new THREE.GLTFLoader();
            loader.load(
                modelUrl,
                function (gltf) {
                    // 加载成功后的处理
                    const model = gltf.scene;
                    
                    // 调整模型大小和位置
                    const box = new THREE.Box3().setFromObject(model);
                    const size = box.getSize(new THREE.Vector3()).length();
                    const center = box.getCenter(new THREE.Vector3());
                    
                    // 获取模型底部的 Y 坐标
                    const bottomY = box.min.y;
                    
                    // 调整模型位置，使底部与 Y=0 平面对齐
                    model.position.x = position.x - center.x;
                    model.position.y = position.y - bottomY;
                    model.position.z = position.z - center.z;
                    
                    // 调整模型缩放
                    model.scale.multiplyScalar(scale);
                    
                    // 寻找机器人头部
                    let robotHead = null;
                    model.traverse(function(object) {
                        // 根据命名约定寻找头部
                        if (object.isMesh && (
                            object.name.toLowerCase().includes('head') || 
                            object.name.toLowerCase().includes('头') ||
                            object.name.toLowerCase().includes('face') ||
                            object.name.toLowerCase().includes('skull') ||
                            object.parent?.name.toLowerCase().includes('head')
                        )) {
                            console.log('找到机器人头部:', object.name);
                            robotHead = object;
                        }
                    });
                    
                    // 如果没有找到明确的头部，尝试寻找最上方的部分
                    if (!robotHead) {
                        let highestY = -Infinity;
                        let highestObject = null;
                        
                        model.traverse(function(object) {
                            if (object.isMesh) {
                                // 计算该网格的世界位置
                                const position = new THREE.Vector3();
                                object.getWorldPosition(position);
                                
                                // 找到Y值最高的网格
                                if (position.y > highestY) {
                                    highestY = position.y;
                                    highestObject = object;
                                }
                            }
                        });
                        
                        if (highestObject) {
                            console.log('使用最高位置的部分作为头部:', highestObject.name);
                            robotHead = highestObject;
                        }
                    }
                    
                    // 如果找到了头部，保存其初始旋转
                    if (robotHead) {
                        robotHead.userData.initialRotation = {
                            x: robotHead.rotation.x,
                            y: robotHead.rotation.y,
                            z: robotHead.rotation.z
                        };
                        
                        // 将头部添加到跟踪列表
                        robotHeads.push({
                            head: robotHead,
                            initialRotation: robotHead.userData.initialRotation
                        });
                    }
                    
                    // 为模型添加或替换材质
                    applyMaterialsToModel(model);
                    
                    // 将模型添加到场景
                    scene.add(model);
                    
                    // 将模型添加到已加载模型列表
                    loadedModels.push({
                        model: model,
                        position: position,
                        box: box,
                        url: modelUrl
                    });
                    
                    // 调整相机位置以查看所有模型
                    adjustCameraToViewAllModels();
                    
                    return model;
                },
                function (xhr) {
                    // 加载进度
                    console.log(`${modelUrl}: ${(xhr.loaded / xhr.total * 100)}% loaded`);
                },
                function (error) {
                    // 加载出错
                    console.error(`加载模型 ${modelUrl} 出错:`, error);
                }
            );
        },
        
        // 获取场景中的所有模型
        getLoadedModels: function() {
            return loadedModels;
        },
        
        // 移除指定模型
        removeModel: function(modelIndex) {
            if (modelIndex >= 0 && modelIndex < loadedModels.length) {
                const modelInfo = loadedModels[modelIndex];
                scene.remove(modelInfo.model);
                
                // 从数组中移除
                loadedModels.splice(modelIndex, 1);
                
                // 更新相机位置
                adjustCameraToViewAllModels();
                
                return true;
            }
            return false;
        },
        
        // 移除所有模型
        removeAllModels: function() {
            loadedModels.forEach(modelInfo => {
                scene.remove(modelInfo.model);
            });
            
            // 清空数组
            loadedModels.length = 0;
            robotHeads.length = 0;
            
            // 重置相机
            camera.position.set(0, 1, 5);
            camera.lookAt(0, 0, 0);
            
            if (controls) {
                controls.update();
            }
        }
    };
    
    // 为模型应用材质的函数
    function applyMaterialsToModel(object) {
        // 递归遍历模型的所有子对象
        object.traverse(function(child) {
            // 检查是否是网格对象
            if (child.isMesh) {
                // 检查是否已有材质
                if (!child.material || child.material.type === 'MeshBasicMaterial') {
                    // 创建PBR材质 (物理基础渲染材质)
                    const material = new THREE.MeshStandardMaterial({
                        color: 0x808080,           // 基础颜色
                        roughness: 0.5,            // 粗糙度 (0=镜面反射, 1=完全漫反射)
                        metalness: 0.5,            // 金属度 (0=非金属, 1=金属)
                        envMapIntensity: 1.0,      // 环境贴图强度
                    });
                    
                    // 应用材质
                    child.material = material;
                } else {
                    // 如果已有材质，可以增强现有材质
                    if (child.material.isMeshStandardMaterial || child.material.isMeshPhysicalMaterial) {
                        // 增强PBR材质属性
                        child.material.roughness = 0.5;
                        child.material.metalness = 0.5;
                        child.material.envMapIntensity = 1.0;
                    } else {
                        // 将非PBR材质转换为PBR材质
                        const oldMaterial = child.material;
                        const newMaterial = new THREE.MeshStandardMaterial({
                            color: oldMaterial.color || 0x808080,
                            map: oldMaterial.map,
                            roughness: 0.5,
                            metalness: 0.5,
                            envMapIntensity: 1.0,
                            normalMap: oldMaterial.normalMap,
                        });
                        child.material = newMaterial;
                    }
                }
                
                // 启用阴影
                child.castShadow = true;
                child.receiveShadow = true;
            }
        });
    }
    
    // 调整相机位置以查看所有模型
    function adjustCameraToViewAllModels() {
        if (loadedModels.length === 0) return;
        
        // 如果只有一个模型，直接调整相机
        if (loadedModels.length === 1) {
            const modelInfo = loadedModels[0];
            const box = modelInfo.box;
            const size = box.getSize(new THREE.Vector3()).length();
            
            camera.position.set(0, size / 3, size);
            camera.lookAt(new THREE.Vector3(0, 0, 0));
            
            if (controls) {
                controls.target.set(0, 0, 0);
                controls.update();
            }
            return;
        }
        
        // 计算所有模型的边界框
        const allModelsBox = new THREE.Box3();
        loadedModels.forEach(modelInfo => {
            // 更新模型的边界框，因为模型可能已被移动或缩放
            const box = new THREE.Box3().setFromObject(modelInfo.model);
            allModelsBox.union(box);
        });
        
        // 计算边界框中心和大小
        const center = allModelsBox.getCenter(new THREE.Vector3());
        const size = allModelsBox.getSize(new THREE.Vector3());
        const maxDim = Math.max(size.x, size.y, size.z);
        
        // 设置相机位置
        const cameraDistance = maxDim * 1.5; // 确保所有模型都在视野内
        camera.position.set(
            center.x, 
            center.y + maxDim / 3, 
            center.z + cameraDistance
        );
        camera.lookAt(center);
        
        // 更新控制器的目标点
        if (controls) {
            controls.target.copy(center);
            controls.update();
        }
    }
}

// 使用图片作为场景背景
function setBackgroundImage(scene, imageUrl) {
    // 创建纹理加载器
    const textureLoader = new THREE.TextureLoader();
    
    // 加载图片纹理
    textureLoader.load(
        imageUrl,
        function(texture) {
            // 设置为场景背景
            scene.background = texture;
        },
        undefined, // 进度回调
        function(error) {
            console.error('加载背景图片出错:', error);
            scene.background = new THREE.Color(0xf0f0f0); // 加载失败时设置默认背景色
        }
    );
}

// 为了兼容旧代码的调用方式
function initGLTFViewer(modelUrl, containerId = 'model-container') {
    const viewer = initModelViewer(containerId);
    viewer.loadModel(modelUrl);
    return viewer;
}